package cs633.action;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

import cs633.util.Album;
import cs633.util.DBManager;

public class UploadAction extends ActionSupport implements ServletRequestAware {
	private static final long serialVersionUID = 1845729398600086918L;
	private HttpServletRequest request;
	private File userImage;
	private String userImageContentType;
	private String userImageFileName;
	private long fileSize;	
	
	HttpSession session;
	
	public long getFileSize() {
		return fileSize;
	}
	public void setFileSize(long fileSize) {
		this.fileSize = fileSize;
	}
	public String upload() {
		session = request.getSession(false);
		String selectedAlbum = request.getParameter("albumName");
		String imageTitle = request.getParameter("imageTitle");
		String imageDesc = request.getParameter("imageDesc");		
		String userID = (String) session.getAttribute("userID");
		String userSeq = (String) session.getAttribute("userSeq");
		String contextPath = null;
		String filePath = null;
		String newAlbumLoc = null;
		ResourceBundle rb = ResourceBundle.getBundle("resource");
		String s3 = rb.getString("s3");
		
		if (userID == null || selectedAlbum.equals("")) 
			return ERROR;
				
		Album album = getAlbum(userID, selectedAlbum);
		String albumLoc = album.getAlbumLoc();
		if (albumLoc == null || albumLoc.trim().length() == 0) {
			albumLoc = RandomStringUtils.random(10, true, false);
			contextPath = userID.concat(File.separator).concat(albumLoc);
			filePath = s3.concat(File.separator).concat("images").concat(File.separator).concat(userID);
			//filePath = request.getSession().getServletContext().getRealPath("/images/"+userID);
			newAlbumLoc = filePath.concat(File.separator+albumLoc);
			
			File newDir = new File(newAlbumLoc);
			if (!newDir.exists()) {
				newDir.mkdir();
			}
			updateAlbumLoc(userSeq, selectedAlbum, contextPath);
		} else {
			newAlbumLoc = s3.concat(File.separator).concat("images").concat(File.separator).concat(albumLoc);
			//newAlbumLoc = request.getSession().getServletContext().getRealPath("/images").concat(File.separator).concat(albumLoc);
		}
		//boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		File fileToCreate = new File(newAlbumLoc, this.userImageFileName);
		try {
			FileUtils.copyFile(this.userImage, fileToCreate);
			checkExistingImage(album.getAlbumId(), getUserImageFileName(), imageTitle, imageDesc);
			//insertImage(album.getAlbumId(), getUserImageFileName());
//			setFileSize(fileToCreate.length());
			
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		return SUCCESS;
	}
	
	private void checkExistingImage(int albumId, String imageName, String imageTitle, String imageDesc) {
		Connection con = null;
		int count = 0;
		try {
			con = DBManager.getInstance().getConn();
			String sql = "SELECT COUNT(*) FROM cs633.user_img WHERE USER_ALBUM_ID = ? AND IMG_NAME = ?";
			PreparedStatement pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, albumId);
			pstmt.setString(2, imageName);
			
			ResultSet rs = pstmt.executeQuery();
			while (rs.next()) {
				count = rs.getInt(1);
			}
			if (count > 0) {
				deleteImage(albumId, imageName);
				insertImage(albumId, imageName, imageTitle, imageDesc);
			} else {
				insertImage(albumId, imageName, imageTitle, imageDesc);
			}
		} catch (Exception e) {
			System.out.println("Error: " + e.getMessage());
		} finally {
			try {
				con.close();
			} catch (Exception e) { }
		}		
	}
	
	private void deleteImage(int albumId, String imageName) {
		Connection con = null;
		try {
			con = DBManager.getInstance().getConn();
			String sql = "DELETE FROM cs633.user_img WHERE USER_ALBUM_ID = ? AND IMG_NAME = ?";
			PreparedStatement pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, albumId);
			pstmt.setString(2, imageName);

			int count = pstmt.executeUpdate();
			
		} catch (Exception e) {
			System.out.println("Error: " + e.getMessage());
		} finally {
			try {
				con.close();
			} catch (Exception e) { }
		}
	}
	
	private void insertImage(int albumId, String imageName, String imageTitle, String imageDesc) {
		Connection con = null;
		try {
			con = DBManager.getInstance().getConn();
			String sql = "INSERT INTO cs633.user_img (`USER_ALBUM_ID`, `IMG_NAME`, `IMG_SIZE`, `IMG_TYPE`, `IMG_DESC`,`IMG_TITLE`) VALUES(?,?,?,?,?,?)";
			PreparedStatement pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, albumId);
			pstmt.setString(2, imageName);
			pstmt.setLong(3, getUserImage().length());
			pstmt.setString(4, getUserImageContentType());
			if (imageDesc == null || imageDesc.trim().length() == 0)
				pstmt.setNull(5, java.sql.Types.VARCHAR);
			else
				pstmt.setString(5, imageDesc);
			
			if (imageTitle == null || imageTitle.trim().length() == 0)
				pstmt.setNull(6, java.sql.Types.VARCHAR);
			else
				pstmt.setString(6, imageTitle);
			
			int count = pstmt.executeUpdate();
			
		} catch (Exception e) {
			System.out.println("Error: " + e.getMessage());
		} finally {
			try {
				con.close();
			} catch (Exception e) { }
		}
	}
	
	private void updateAlbumLoc(String userSeq, String name, String path) {
		Connection con = null;
		try {
			con = DBManager.getInstance().getConn();
			String sql = "INSERT INTO cs633.user_album(`USER_SEQ_ID`, `ALBUM_NAME`, `ALBUM_LOC`) VALUES (?, ? ,?)";
			PreparedStatement pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, Integer.parseInt(userSeq));
			pstmt.setString(2, name);
			pstmt.setString(3, path);
			
			int count = pstmt.executeUpdate();
			
		} catch (Exception e) {
			System.out.println("Error: " + e.getMessage());
		} finally {
			try {
				con.close();
			} catch (Exception e) { }
		}
	}
	
	private Album getAlbum(String userID, String albumName) {
		String loc = null;
		int id = 0;
		Connection con = null;
		Album album = new Album();
		try {
			con = DBManager.getInstance().getConn();
			String sql = "SELECT USER_ALBUM_ID, ALBUM_LOC FROM cs633.user U, cs633.user_album A WHERE U.USER_SEQ_ID = A.USER_SEQ_ID AND U.USER_ID = ? AND A.ALBUM_NAME = ?";
			PreparedStatement pstmt = con.prepareStatement(sql);
			pstmt.setString(1, userID);
			pstmt.setString(2, albumName);
			
			ResultSet rs = pstmt.executeQuery();
			while (rs.next()) {
				loc = rs.getString("ALBUM_LOC");
				id = rs.getInt("USER_ALBUM_ID");
			}
			album.setAlbumLoc(loc);
			album.setAlbumId(id);
			con.close();
		}
		catch (Exception e) {
			System.out.println("Error: " + e.getMessage());
		} 
		finally {
			try {
				con.close();
			} catch (Exception e) {
				
			}
		}
		return album;
	}
	
	
    public File getUserImage() {
        return userImage;
    }
 
    public void setUserImage(File userImage) {
        this.userImage = userImage;
    }
 
    public String getUserImageContentType() {
        return userImageContentType;
    }
 
    public void setUserImageContentType(String userImageContentType) {
        this.userImageContentType = userImageContentType;
    }
 
    public String getUserImageFileName() {
        return userImageFileName;
    }
 
    public void setUserImageFileName(String userImageFileName) {
        this.userImageFileName = userImageFileName;
    }
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;		
	}
}
